package com.tao.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tao.content.domain.dto.CourseCategoryDto;
import com.tao.content.domain.pojo.CourseCategory;
import com.tao.content.domain.vo.CourseCategoryVo;
import com.tao.content.mapper.CourseCategoryMapper;
import com.tao.content.service.ICourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author taohongrun
 * @since 2024-11-01
 */
@Service
@Slf4j
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements ICourseCategoryService {
    @Override
    public List<CourseCategoryVo> queryTreeNodes() {
        List<CourseCategoryDto> allNodeList = lambdaQuery()
                .orderByAsc(CourseCategory::getOrderby)
                .list()
                .stream()
                .map(m -> {
                    CourseCategoryDto courseCategoryDto = new CourseCategoryDto();
                    BeanUtils.copyProperties(m, courseCategoryDto);
                    return courseCategoryDto;
                })
                .toList();
        // 分离一级节点和子节点
        List<CourseCategoryDto> firstNodeList = allNodeList.stream()
                .filter(f -> "1".equals(f.getParentid()))
                .toList();

        List<CourseCategoryDto> allChildrenNodeList = allNodeList.stream()
                .filter(f -> !"1".equals(f.getParentid()))
                .toList();
        log.info("一级节点数据为:{}",firstNodeList);
        log.info("所有字节点数据为:{}",allChildrenNodeList);
        for (CourseCategoryDto firstNode : firstNodeList) {
            setChildrenNodes(firstNode, allChildrenNodeList);
            log.info("节点:{}的孩子节点为:{}",firstNode,firstNode.getChildrenNodes());
        }


        return firstNodeList.stream()
                .map(m -> {
                    CourseCategoryVo courseCategoryVo = new CourseCategoryVo();
                    BeanUtils.copyProperties(m,courseCategoryVo);
                    return courseCategoryVo;
                })
                .toList();
    }

    private void setChildrenNodes(CourseCategoryDto parent, List<CourseCategoryDto> allChildren) {
        if (parent.getIsLeaf() == 1) return;
        parent.setChildrenNodes(allChildren.stream()
                .filter(f -> f
                        .getParentid().equals(parent.getId()))
                .toList());
        parent.getChildrenNodes().forEach(p -> setChildrenNodes(p,allChildren));
    }
}
